<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NPopconfirm,
  NTreeSelect,
  NTag, NFlex,NCard
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'

import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import {forEach} from "lodash-es";

defineOptions({ name: '培育模板' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '培育模板',
  initForm: {},
  doCreate: api.createGrow,
  doUpdate: api.updateGrow,
  doDelete: api.deleteGrow,
  refresh: () => $table.value?.handlerefresh(),
})
const data = reactive({
  growOption: [
    {
      value: 1,
      label: '比例',
    },
    {
      value: 2,
      label: '固定金额',
    },
  ],
  customer_level: [],
  routers: [
    {
      name: '',
      type: '',
      num: '',
    },
  ],
})
const deptOption = ref([])
const isDisabled = ref(false)
const onCreate = () => {
  return {
    name: '',
    level: '',
    num: '',
  }
}
onMounted(() => {
  $table.value?.handleSearch()
  getcosutomer_level()
})
async function getcosutomer_level() {
  let ret = await api.getCustomerLevel()
  data.customer_level = ret.data
}
async function hanbeSumit() {
  console.log(1, 'modalForm')
}

const deptRules = {
  name: [
    {
      required: true,
      message: '请输入模板称',
      trigger: ['input', 'blur', 'change'],
    },
  ],
}

async function addDepts() {
  isDisabled.value = false
  handleAdd()
}

function get_level_name(id){
  let ret = ""
  data.customer_level.forEach((item) => {
    if (item.value === id) {
      ret = item.label
    }
  })
  return ret
}

const columns = [
  {
    title: '+',
    width: 100,
    align: 'center',
    type: 'expand',
    expandable: row => row.routers !== null,
    renderExpand: (row) => {
      let routers = row.routers ?? []
      let group = []
      let dw = "元"
      if(row.type===1){
        dw = "%"
      }
      for (let i = 0; i < routers.length; i++){
        let title = get_level_name(routers[i].name)
        let con = title+routers[i].level+"级:"+routers[i].num+dw
        group.push(
          h(NButton, { type: "primary" ,size:"small",dashed:true,style:{} }, { default: () => con})
        )
      }
      return h(NFlex, group)
    }
  },
  {
    title: 'ID',
    key: 'id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '名称',
    key: 'name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '佣金类型',
    key: 'type',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
          { default: () => (row.type == 1 ? '比例' : '固定金额') }
      )
    },
  },
  {
    title: '创建时间',
    key: 'created_at',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
  },
  {
    title: '操作',
    key: 'actions',
    width: 'auto',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
            h(
                NButton,
                {
                  size: 'small',
                  type: 'primary',
                  style: 'margin-right: 8px;',
                  onClick: () => {
                    console.log('row', row.parent_id)
                    if (row.parent_id === 0) {
                      isDisabled.value = true
                    } else {
                      isDisabled.value = false
                    }
                    handleEdit(row)
                  },
                },
                {
                  default: () => '编辑',
                  icon: renderIcon('material-symbols:edit', { size: 16 }),
                }
            ),
            [[vPermission, 'post/api/content/category/update']]
        ),
        h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete({ data_id: row.id }, false),
              onNegativeClick: () => {},
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {
                            default: () => '删除',
                            icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                          }
                      ),
                      [[vPermission, 'delete/api/content/category/delete']]
                  ),
              default: () => h('div', {}, '确定删除该分类吗?'),
            }
        ),
      ]
    },
  },
]
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="培育模板列表">
    <template #action>
      <div>
        <NButton
            v-permission="'post/api/content/category/create'"
            class="float-right mr-15"
            type="primary"
            @click="addDepts"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建培育模板
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getGrow"
        default-expand-all
    >
      <template #queryBar>
        <QueryBarItem label="培育模板" :label-width="80">
          <NInput
              v-model:value="queryItems.name"
              clearable
              type="text"
              placeholder="请输入培育模板名称"
              @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal
        v-model:visible="modalVisible"
        :title="modalTitle"
        :loading="modalLoading"
        style="width: 700px !important"
        @save="handleSave"
    >
      <NForm
          ref="modalFormRef"
          label-placement="left"
          label-align="left"
          :label-width="80"
          :model="modalForm"
          :rules="deptRules"
          @submit="hanbeSumit"
      >
        <NFormItem label="模版名称" path="name">
          <NInput v-model:value="modalForm.name" clearable placeholder="请输入名称" />
        </NFormItem>
        <NFormItem label="佣金类型" path="type">
          <n-radio-group v-model:value="modalForm.type" name="radiogroup" :default-value="1">
            <n-space>
              <n-radio v-for="song in data.growOption" :key="song.value" :value="song.value">
                {{ song.label }}
              </n-radio>
            </n-space>
          </n-radio-group>
        </NFormItem>
        <NFormItem label="佣金设定" path="routers">
          <n-layout>
            <n-layout-header>
              <n-flex>
                <n-tag size="large" style="width: 100px"> 会员等级 </n-tag>
                <n-tag size="large" style="width: 120px"> 收益层级 </n-tag>
                <n-tag size="large" style="width: 100px;"> 收益 </n-tag>
              </n-flex>
            </n-layout-header>
            <n-layout-content content-style="padding: 10px 0;">
              <n-dynamic-input v-model:value="modalForm.routers" :on-create="onCreate">
                <template #default="{ value }">
                  <n-flex justify="space-between">
                    <n-select
                        style="width: 100px"
                        v-model:value="value.name"
                        :options="data.customer_level"
                        placeholder="请选择会员等级"
                    />
                    <n-input-number button-placement="both"
                                    v-model:value="value.level"
                                    style="width: 120px"
                                    min="0"
                                    max="3"
                                    placeholder="收益层级"
                    />
                    <n-input
                        v-model:value="value.num"
                        type="text"
                        style="width: 100px"
                        placeholder="收益"
                    >
                      <template #suffix v-if="modalForm.type == 2"> 元 </template>
                      <template #suffix v-else> % </template>
                    </n-input>
                  </n-flex>
                </template>
              </n-dynamic-input>
            </n-layout-content>
          </n-layout>

        </NFormItem>
      </NForm>
    </CrudModal>
  </CommonPage>
</template>
